﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Xpo;
using DevExpress.Data;
using System.Collections;
using DevExpress.Data.Access;

namespace ChuanPlus.DAO
{
    class RejectionDAO
    {
        //
        // save an Rejection to database, 'stockCard',stock quantity as 1 UnitOfWork
        //
        public static void save(Rejection Rejection) //ok
        {
            Session.DefaultSession.BeginTransaction();
            RejectionDetails reDetail = null;
            Stock stockObj = null;
            Product product = null;
            // lay TransactionType 
            XPQuery<TransactionType> transtype = new XPQuery<TransactionType>(Session.DefaultSession);
            var listTrans = from t in transtype
                            where t.TransactionTypeID == 4
                            select t;
            List<TransactionType> arr = new List<TransactionType>(listTrans.AsEnumerable<TransactionType>());
            TransactionType transtypeObj = arr[0];
            try
            {
                //-------- Tao stockcard de bao' viec wang hang` lai dzo kho ----------- 

                int count = Rejection.RejectionDetails.Count();
                StockCard st;
                for (int i = 0; i < count; i++)
                {
                    //// Cong QtyBalance cho Stock ung voi Product va Warehouse & set balance cho stockcard
                     reDetail = Rejection.RejectionDetails[i];
                     stockObj = reDetail.StockID;
                     product = reDetail.StockID.ID;
                    // set QtyBalance va balance cua Stockcard
                    double balance = stockObj.QtyBalance + reDetail.Quantity;
                    stockObj.QtyBalance = balance;
                    stockObj.Save();

                    //xet hoa don do, cong dzo bang Product
                    // tam thoi lam tuong tu Invoice
                    double redInvQty;
                    if (product.DistributorID.DistributorName.Equals("CBD"))
                    {
                        redInvQty = 0;
                    }
                    else
                    {
                        redInvQty = reDetail.Quantity;
                    }
                    product.RedInvQty += redInvQty;
                    product.Save();


                    // Luu stockcard
                    long StockCardID = StockCardDAO.GenerateId();
                    st = new StockCard(Session.DefaultSession,++StockCardID, stockObj, DateTime.Now, reDetail.Quantity, 0.0f, balance, transtypeObj, Rejection.RejectID.ToString());
                    st.Save();
                    //remark dzo cai Order
                    Rejection.DONo.Remark += " Rejected ";
                    Rejection.DONo.Save();
                }
                //--------    Tru lai Customer Credit
                double custCredit = Rejection.DONo.CustomerID.Credit;
                if (custCredit < Rejection.Total)
                {
                    if (custCredit == 0)
                    {
                        Rejection.PayoutAmount = Rejection.Total;
                    }
                    else
                    {
                        Rejection.DONo.CustomerID.Credit = 0;
                        Rejection.PayoutAmount = Rejection.Total - custCredit;
                    }
                }
                else
                    Rejection.DONo.CustomerID.Credit -= Rejection.Total;
                Rejection.DONo.CustomerID.Save();
                Rejection.DONo.PayInAdvance += Rejection.Total;
                Rejection.Status = "P";
                Rejection.Save();
                Session.DefaultSession.CommitTransaction();
                
            }
            catch (Exception e)
            {
                Session.DefaultSession.RollbackTransaction();
                throw new Exception(e.Message);                
            }
            
        }
        public static List<Rejection> getRejections(string status)
        {
            try
            {
                XPQuery<Rejection> rejection = new XPQuery<Rejection>(Session.DefaultSession);
                var list = from r in rejection
                           where r.Status == status
                           select r;
                return new List<Rejection>(list.AsEnumerable<Rejection>());
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        //
        // update an Rejection to database, 'stockCard', stock quantity as 1 UnitOfWork
        //  optional method
        public static bool update(Rejection Rejection)
        {
            return true;
        }
        public static List<Rejection> GetAllRejections() //ok
        {
            XPQuery<Rejection> Rejections = new XPQuery<Rejection>(Session.DefaultSession);
            var list = from prod in Rejections
                       select prod;
            List<Rejection> arr = new List<Rejection>(list.AsEnumerable<Rejection>());
            try
            {
                return arr;
            }
            catch (Exception e) { return null; }
        }

        //
        //return list of Rejection by RejectionDate base on fromDate, toDate
        // order by RejectionDate DESC
        public static List<Rejection> GetRejectionByDate(DateTime fromDate, DateTime toDate) //ok
        {
            XPQuery<Rejection> rejections = new XPQuery<Rejection>(Session.DefaultSession);
            var list = from r in rejections
                       where ((r.RejectDate >= fromDate) && (r.RejectDate <= toDate))
                       orderby r.RejectDate descending
                       select r;
            List<Rejection> arr = new List<Rejection>(list.AsEnumerable<Rejection>());
            try
            {
                return arr;
            }
            catch (Exception e) { return null; }

        }
        //
        //return list of Rejection by RejectionDate base on Rejection Number
        // order by RejectionDate DESC
        //modify kieu parameter String -> int
        public static Rejection GetRejectionByNo(int RejectionNo) //ok
        {
            XPQuery<Rejection> rejections = new XPQuery<Rejection>(Session.DefaultSession);
            var list = from r in rejections
                       where r.RejectID == RejectionNo
                       orderby r.RejectDate descending
                       select r;
            List<Rejection> arr = new List<Rejection>(list.AsEnumerable<Rejection>());
            try
            {
                return arr[0];
            }
            catch (Exception e) { return null; }
        }
    }
}
